package com.mojo.concurrent.concurrent_07_pool;

import java.util.concurrent.*;

/**
 * 自定义线程池示例
 *
 * @author <a href="mailto:sjj@jianzhimao.com">mojo</a>
 * copyright (C), 2013-2021, 广州九尾信息科技有限公司
 * @date 2021/8/19 14:47
 */
public class DefinedThreadPool {
    //创建ThreadFactory
    static ThreadFactory tf = t -> new Thread(t, "defined-pool--");
    //创建线程池
    static ThreadPoolExecutor pool = new ThreadPoolExecutor(8, 16, 10L,
            TimeUnit.SECONDS, new ArrayBlockingQueue<>(4),
            //tf,
            //Executors.defaultThreadFactory(),
            new MyThreadFactory(),
            new ThreadPoolExecutor.CallerRunsPolicy());

    public static void main(String[] args) throws InterruptedException {
        //执行线程
        //Thread t = new Thread(() -> {
        for (int i = 0; i < 50; i++) {
            final int n = i;
            pool.execute(() -> {
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println(Thread.currentThread().getName() + ">>" + n);
            });
        }
        //});
        //t.start();
        //t.join();
        pool.shutdown();
        System.out.println("线程池中断" + pool.awaitTermination(10, TimeUnit.SECONDS));
        //停止线程池
        Thread.sleep(5000L);
        System.out.println("=============================================");
        System.out.println("getPoolSize:" + pool.getPoolSize());
        System.out.println("getCorePoolSize:" + pool.getCorePoolSize());
        System.out.println("getActiveCount:" + pool.getActiveCount());
        System.out.println("getMaximumPoolSize:" + pool.getMaximumPoolSize());
        System.out.println("getCompletedTaskCount:" + pool.getCompletedTaskCount());
        System.out.println("queue size:" + pool.getQueue().size());
        Thread.sleep(10000L);
        System.out.println("=============================================");
        System.out.println("getPoolSize:" + pool.getPoolSize());
        System.out.println("getCorePoolSize:" + pool.getCorePoolSize());
        System.out.println("getActiveCount:" + pool.getActiveCount());
        System.out.println("getMaximumPoolSize:" + pool.getMaximumPoolSize());
        System.out.println("getCompletedTaskCount:" + pool.getCompletedTaskCount());
        System.out.println("queue size:" + pool.getQueue().size());
    }
}
